#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;

//分片结构体
struct Fragment {
    int length;//分片长度（字节）
    int offset;//偏移量（字节）
};

vector<Fragment> fragmentPacket(int packetLength, const vector<int>& pathMTUs)
{
    vector<Fragment> fragments;
    if (pathMTUs.empty() || packetLength <= 0) return fragments;

    //找到路径中最小的MTU（路径MTU）
    int pathMTU = *min_element(pathMTUs.begin(), pathMTUs.end());
    
    //每个分片的数据部分最大长度（减去20字节的头部）
    int maxDataLength = pathMTU - 20;
    if (maxDataLength <= 0) return fragments;//MTU太小，无法容纳头部，返回空（实际应用中可能需要错误处理）

    //原始数据长度（总长度减去头部）
    int dataLength = packetLength - 20;
    if (dataLength <= 0)
	{
        //报文长度太小，返回整个报文作为一个分片
        fragments.push_back({packetLength, 0});
        return fragments;
    }

    //计算需要的分片数量
    int numFragments = (dataLength + maxDataLength - 1) / maxDataLength;
    
    //生成分片
    for (int i = 0; i < numFragments; i++)
	{
        int offset = i * maxDataLength;
        int remaining = dataLength - offset;
        int fragDataLength = min(maxDataLength, remaining);
        
        //分片总长度=数据长度+20字节头部
        fragments.push_back({fragDataLength + 20, offset});
    }

    return fragments;
}

int main()
{
    //示例1：1500字节MTU，2000字节报文
    vector<int> mtu1 = {1500};
    auto fragments1 = fragmentPacket(2000, mtu1);
    
    cout << "Example 1:" << endl;
    for (const auto& frag : fragments1)
	{
        cout << "Length: " << frag.length << ", Offset: " << frag.offset << endl;
    }
    
    //示例2：多跳路径，1400字节MTU，3000字节报文
    vector<int> mtu2 = {1500, 1400, 1500};
    auto fragments2 = fragmentPacket(3000, mtu2);
    
    cout << "\nExample 2:" << endl;
    for (const auto& frag : fragments2)
	{
        cout << "Length: " << frag.length << ", Offset: " << frag.offset << endl;
    }
    
    return 0;
}